package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Transactional
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Override
    public void saveOrder(Order order) {
        //1.通过user进行查询购物车信息
        User user = UserHolder.get();
        Long userId = user.getId();
        Long orderId = IdWorker.getId();
        //2.查询购物车,如果为空则报错
        List<Cart> cartList = cartService.findCartList();
        if (CollectionUtil.isEmpty(cartList)){
            throw new CustomException("对不起，你的购物车中没有菜品");
        }
        //3.查询收货地址，如果为空则报错
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null){
            throw new CustomException("您为选择收货地址");
        }
        //4.1保存订单详情数据
        BigDecimal amount = new BigDecimal(0);

        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setImage(cart.getImage());
            orderDetail.setName(cart.getName());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setOrderId(orderId);
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetailMapper.insert(orderDetail);
            amount.add(amount.multiply(cart.getAmount().multiply(new BigDecimal(cart.getNumber()))));
        }
        //4.2保存订单数据
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);
        order.setUserId(userId);
        //order.setAddressId();
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());//to do 等支付写完
        //order.setPayMethod(1);
        order.setAmount(amount);
        //order.setRemark();
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.isNotEmpty(address.getProvinceName() ) ? address.getProvinceName() : "");
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ?  address.getDetail() : "");
        order.setAddress(sb.toString());
        order.setConsignee(address.getConsignee());
        //order.setPayUrl();
        orderMapper.insert(order);
        //清除购物车
        cartService.cleanCart();
    }

    @Override
    public Page<Order> findPage(Integer pageNum, Integer pageSize) {
        //首先通过userid获取page数据
        Page<Order> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        //wrapper.orderByDesc(Order::getOrderTime);
        page = orderMapper.selectPage(page, wrapper);
        //再获取每个order的details
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)){
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId,order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetails);
            }
        }
        return page;
    }

    @Override
    public Page<Order> findPage2(Integer pageNum, Integer pageSize, Long number, String beginTime, String endTime) {
        //首先通过userid获取page数据
        Page<Order> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq( number != null ,Order::getNumber,String.valueOf(number));
        //日期转换
        wrapper.between(StringUtils.isNotEmpty(beginTime),Order::getOrderTime,beginTime,endTime);
        page = orderMapper.selectPage(page, wrapper);
        return page;
    }
}
